package com.yueshop.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yueshop.common.mq.StockDetailTo;
import com.yueshop.common.mq.StockLockedTo;
import com.yueshop.common.to.OrderTo;
import com.yueshop.common.to.SkuHasStockVo;
import com.yueshop.common.utils.R;
import com.yueshop.ware.entity.WareOrderTaskDetailEntity;
import com.yueshop.ware.entity.WareOrderTaskEntity;
import com.yueshop.ware.exception.NoStockException;
import com.yueshop.ware.feign.OrderFeignService;
import com.yueshop.ware.feign.ProductFeignService;
import com.yueshop.ware.service.WareOrderTaskDetailService;
import com.yueshop.ware.service.WareOrderTaskService;
import com.yueshop.ware.vo.OrderItemVo;
import com.yueshop.ware.vo.OrderVo;
import com.yueshop.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.ware.dao.WareSkuDao;
import com.yueshop.ware.entity.WareSkuEntity;
import com.yueshop.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private OrderFeignService orderFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId:
         * wareId:
         */
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //通过skuid 和wareId 查询该仓库是否有这个商品的库存
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        //没有这个商品 新增
        if(wareSkuEntities==null ||wareSkuEntities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if(info.getCode()==0){
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            wareSkuDao.insert(wareSkuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            //查询当前sku 的库存量 SELECT  SUM(stock-stock_locked) FROM `wms_ware_sku` WHERE sku_id=5
            Long count = baseMapper.getSkuStock(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 1.下单成功了,订单过期没有支付被系统自动取消了 或者用户手动取消
     * 2. 下订单成功,库存锁定成功,远程扣减积分异常 订单回滚,自动解锁库存
     * @param vo
     * @return
     */
    //锁定库存
    @Transactional
    @Override
    public Boolean  orderLockStock(WareSkuLockVo vo) {

        //0保存库存工作单,方便追溯库存锁定情况
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);



        //1.按照下单的收货地址, 找就近仓库锁库存
        //2.找到每个商品在那个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(orderItemVo -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(orderItemVo.getSkuId());
            skuWareHasStock.setNum(orderItemVo.getCount());
            //查询该商品在哪些仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(orderItemVo.getSkuId());
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //为每个商品锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareId = hasStock.getWareId();
            if(wareId==null ||wareId.size()==0){
                //没有任何仓库有这个商品库存
                throw  new NoStockException(skuId);
            }
            for (Long aLong : wareId) {
              Long count =  wareSkuDao.lockSkuStock(skuId,aLong,hasStock.getNum());
              if(count==1){
                  //返回影响行数是1 锁定成功了,
                  skuStocked=true;
                  WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),wareOrderTaskEntity.getId(),aLong,1);
                  wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                  //通知RabbitMq 锁定了库存
                  StockLockedTo stockLockedTo = new StockLockedTo();
                  stockLockedTo.setTaskId(wareOrderTaskEntity.getId());
                  StockDetailTo stockDetailTo = new StockDetailTo();
                  BeanUtils.copyProperties(wareOrderTaskDetailEntity,stockDetailTo);
                  stockLockedTo.setTaskDetail(stockDetailTo);
                  rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                  break;
              }
            }
            if(skuStocked==false){
                //当前商品所有仓库都没锁住
                throw new NoStockException(skuId);
            }

        }
        //只要没抛异常就全部锁定成功了
        return true;
    }
    //解锁库存
    @Override
    public void unlock(StockLockedTo stockLockedTo) {
        StockDetailTo taskDetail = stockLockedTo.getTaskDetail();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(taskDetail.getId());
        //1.如果工作单详情不为空 说明该库存锁定成功
        if(detailEntity!=null){
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(stockLockedTo.getTaskId());
            R r = orderFeignService.getOrderByOrderSn(taskEntity.getOrderSn());
            if(r.getCode()==0){
                OrderVo order = r.getData(new TypeReference<OrderVo>() {
                });
                //如果没有这个订单 或者订单状态是已经关闭 解锁库存
                if(order==null || order.getStatus()==4){
                    //为了保证幂等性, 只有当工作单详情处于被锁定的情况下才可以进行解锁
                    if(detailEntity.getLockStatus()==1){
                        //当前的工作单详情, 如果是状态1 就是被锁定, 才可以解锁
                        unlockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
                    }
                }

            }else {
                //远程调用失败了 将消息放回队列中 , 让别人继续消息.
                throw new RuntimeException("远程调用订单服务失败");
            }
        }else {
            //查询不到工作单详情,就是回滚了, 无须解锁
        }


    }
    /*
        取消订单,解锁库存
        防止因为订单服务卡顿, 导致订单状态一直概不了, 库存消息优先于订单消息过期
        导致当前卡顿的订单永远不能解锁库存
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查询最新的库存状态,防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderTaskEntity.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity wareOrderTaskDetailEntity : list) {
            unlockStock(wareOrderTaskDetailEntity.getSkuId(),wareOrderTaskDetailEntity.getWareId(),wareOrderTaskDetailEntity.getSkuNum(),wareOrderTaskDetailEntity.getId());
        }
    }


    private void unlockStock(Long skuId, Long wareId, Integer num,Long id) {
        //解锁
        baseMapper.unlockStock(skuId,wareId,num);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(id);
        wareOrderTaskDetailEntity.setLockStatus(2);//更改状态为已解锁
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }


    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}